package com.android.hedgehog.puzzles;

import java.util.Random;

public class CardMatchField {
	Random rand = new Random();
	int totalTurns;
	Card[] card;
	int difficulty;
	int numOfCards;
	int holder1, holder2, temp;
	int totalRows;
	boolean flag;

	public CardMatchField(int difficulty) {
		// numOfCards = 8 + (((difficulty - 1) / 2) * 2);// 8,10,12,14,16
		numOfCards = 8;
		totalTurns = 15 - difficulty;
		if (difficulty > 2) {
			numOfCards = 12;
			totalTurns = 19 - difficulty;
		}
		if (difficulty > 6) {
			numOfCards = 16;
			totalTurns = 23 - difficulty;
		}
		totalRows = numOfCards / 4;

		card = new Card[numOfCards];

		shuffle(); // set up card order;
		placement();

	}

	private void shuffle() {

		for (int i = 0; i < card.length; i++) {
			card[i] = new Card(i / 2);
		}// 00,11,...,NN

		for (int i = 0; i < card.length * 10; i++) {
			holder1 = rand.nextInt(card.length);
			holder2 = rand.nextInt(card.length);

			temp = card[holder1].value;
			card[holder1].value = card[holder2].value;
			card[holder2].value = temp;
		}
	}

	private void placement() {
		for (int i = 0; i < totalRows; i++) { // 8 cards
			for (int j = 0; j < 4; j++) {
				card[j + (i * 4)].x = 40 + (j * 60);
				card[j + (i * 4)].y = 90 + (i * 85);
			}
		}// 8 cards
	}

	public boolean isMatch() {
		flag = false;

		for (int i = 0; i < card.length; i++) {// GRABS flipped cards
			if (card[i].flipped == true) {
				if (flag == false) {
					holder1 = i;
					flag = true;
				} else {
					holder2 = i;
				}

			}
		}// GRABS flipped cards;

		if (card[holder1].value == card[holder2].value) { // match
			card[holder1].matched = true;
			card[holder2].matched = true;
			return true;
		} // match

		return false;

	}

	public void reset() {
		for (int i = 0; i < card.length; i++) {
			card[i].flipped = false;
		}
	}

	public boolean isComplete() { // Returns true if entire deck matched
		temp = 0;
		for (int i = 0; i < card.length; i++) {
			if (card[i].matched == true) {
				temp++;
			}
		}
		if (temp == card.length) {
			return true;
		}
		return false;

	}

}
